<template>
  <div class="goods-container">
    <!-- 顶部操作栏 -->
    <div class="filter-container">
      <!-- 添加商品按钮 -->

      <!-- 分类筛选 -->
      <el-select v-model="filter.category" placeholder="选择分类" class="filterSelecter">
        <el-option
          v-for="item in categoryOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <!-- 供应商编码筛选 -->
      <!-- 商品上下架状态筛选 -->
      <el-select
        v-model="filter.isOnline"
        placeholder="选择上下架状态"
        class="filterSelecter"
      >
        <el-option label="上架" value="1" />
        <el-option label="下架" value="0" />
      </el-select>

      <el-select v-model="filter.supply" placeholder="选择供应商" class="filterSelecter">
        <el-option
          v-for="item in supplyerOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <!-- 商品名称筛选 -->
      <el-input
        v-model="filter.mealName"
        placeholder="输入商品名称"
        class="filterSelecter"
      />

      <!-- 查询按钮 -->
      <el-button type="primary" @click="handleSearch"> 查询 </el-button>

      <el-button type="primary" @click="handleAdd"> 添加商品 </el-button>
    </div>

    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        :header-cell-style="{ background: '#f5f7fa', color: '#909399' }"
        height="75vh"
      >
        <!-- 商品ID -->
        <el-table-column prop="id" label="商品ID" width="80" align="center" />

        <!-- 商品名称 -->
        <el-table-column prop="name" label="商品名称" min-width="150" />

        <!-- 商品描述 -->
        <el-table-column prop="mealdesc" label="商品描述" min-width="150" />
        <!-- 库存数量 -->
        <!-- <el-table-column prop="stock" label="库存数量" width="120" align="center">
				<template #default="scope">
					<el-tag type="success">{{ scope.row.stock }}</el-tag>
				</template>
			</el-table-column> -->

        <!-- 供应商 -->
        <el-table-column prop="supplier" label="供应商" width="150" align="center">
          <template #default="scope">
            {{ getSupplyerName(scope.row.supplyer) }}
          </template>
        </el-table-column>

        <!-- 分类 -->
        <el-table-column prop="category" label="分类" width="150" align="center">
          <template #default="scope">
            {{ getCategoryName(scope.row.category) }}
          </template>
        </el-table-column>

        <!-- 排序 -->
        <el-table-column prop="seq" label="排序" width="80" align="center" />

        <!-- 上下架状态 -->
        <el-table-column prop="is_online" label="上下架状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.is_online === 1 ? 'success' : 'info'">
              {{ scope.row.is_online === 1 ? "上架" : "下架" }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 主图 -->
        <el-table-column label="主图" width="120" align="center">
          <template #default="scope">
            <!-- <el-image
              v-if="scope.row.pictureList && scope.row.pictureList.length > 0"
              :src="scope.row.pictureList[0].url"
              fit="cover"
              :preview-src-list="[scope.row.pictureList[0].url]"
              style="width: 60px; height: 60px"
            /> -->
            <div class="demo-image__preview">
              <el-image
			  v-if="scope.row.pictureList && scope.row.pictureList.length > 0"
                style="width: 100px; height: 100px"
                :src="scope.row.pictureList[0].url"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="getImageUrl(scope.row.pictureList)"
                show-progress
                :initial-index="4"
                fit="cover"
				:preview-teleported="true"
              />
			  <span v-else>无主图</span>
            </div>
          </template>
        </el-table-column>

        <!-- 规格 -->
        <el-table-column label="规格名称">
          <template #default="scope">
            <el-table :data="scope.row.spec" :show-header="false">
              <el-table-column prop="specname" label="名称"> </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column label="商品库存">
          <template #default="scope">
            <el-table :data="scope.row.spec" :show-header="false">
              <el-table-column prop="stock" label="库存"> </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column label="商品价格">
          <template #default="scope">
            <el-table :data="scope.row.spec" :show-header="false">
              <el-table-column prop="price" label="价格"> </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div>
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :small="false"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 商品编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="商品编辑" width="60%">
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品描述" prop="mealdesc">
          <el-input
            v-model="form.mealdesc"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <!-- 库存数量 -->
        <!-- <el-form-item label="库存数量" prop="stock">
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item> -->

        <!-- 供应商 -->
        <el-form-item label="供应商" prop="supplyer">
          <el-select v-model="form.supplyer" placeholder="请选择供应商">
            <el-option
              v-for="item in supplyerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 分类 -->
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 排序 -->
        <el-form-item label="排序" prop="seq">
          <el-input-number v-model="form.seq" :min="1" />
        </el-form-item>

        <!-- 排序 -->
        <el-form-item label="是否上架" :required="true">
          <!-- <span>{{ form.is_online }}</span> -->
          <el-switch v-model="form.is_online" :active-value="1" :inactive-value="0" />
        </el-form-item>

        <!-- 商品图片 -->
        <el-form-item label="商品图片">
          <meal-picture-uploader v-model="form.pictureList" />
        </el-form-item>
        <el-form-item label="规格">
          <!-- <DynamicSpecs /> -->
        </el-form-item>
        <!-- 规格 -->
        <el-form-item label="规格" :required="true">
          规格的类名
          <div class="addSpecButton">
            <el-button type="primary" @click="addSpec">添加规格</el-button>
          </div>

          <draggable
            :list="form.spec"
            item-key="id"
            ghost-class="ghost"
            chosen-class="chosenClass"
            animation="300"
            @end="onSpecEnd"
          >
            <template #item="{ element, index }">
              <div
                style="
                  margin-top: 10px;
                  border: 1px solid #ddd;
                  padding: 8px;
                  border-radius: 5px;
                "
              >
                <el-row :gutter="24">
                  <el-col :span="10">
                    <el-form-item :required="true" label="规格名称">
                      <el-input v-model="element.specname" placeholder="请输入规格名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item :required="true" label="商品价格">
                      <el-input v-model="element.price" type="number" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item :required="true" label="商品库存">
                      <el-input v-model="element.stock" type="number" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4" style="padding-left: 50px">
                    <el-button type="danger" size="small" @click="removeSpec(index)"
                      >删除</el-button
                    >
                  </el-col>
                </el-row>
              </div>
            </template>
          </draggable>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="footer">
          <el-button @click="dialogVisible = false" class="button">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)" class="button"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import draggable from "vuedraggable";
import MealPictureUploader from "@/components/uploader/MealPictureUploader.vue";
import { addGoods, getGoodsList, deleteGoods, editGoods } from "@/api/merchandise";
import { getCategoryList } from "@/api/category";
import { getSupplierListAPI } from "@/api/supplier";
import { SupplierItem } from "@/api/types/supplier";
import type {
  AddGoodsRequest,
  GoodsItem,
  SpecItem,
  PictureItem,
  GetGoodsListParams,
  DeleteGoodsRequest,
  GoodsListResponse,
  EditGoodsRequest,
} from "@/api/types/merchandise";
import DynamicSpecs from "@/components/merchandiseManagement/DynamicSpecs.vue";

// 使用从类型定义文件引入的接口
interface Option {
  id: number;
  name: string;
}
const filter = reactive({
  category: 7, // 默认分类ID为7
  mealName: "", // 新增：商品名称
  supply: "", // 新增：供应商编码
  isOnline: "1", // 新增：商品上下架状态
});
// 表格数据（使用GoodsItem类型）
const tableData = ref<GoodsItem[]>([]);
// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
// 初始化加载商品列表
const loadGoodsData = async (page?: number, size?: number) => {
  const currentPage = typeof page === "number" ? page : pagination.currentPage;
  const currentSize = typeof size === "number" ? size : pagination.pageSize;

  const params: GetGoodsListParams = {
    page: currentPage.toString(),
    size: currentSize.toString(),
    category: filter.category, // 使用筛选条件中的分类
    is_online: filter.isOnline, // 新增参数：商品上下架状态
    meal_name: filter.mealName, // 新增参数：商品名称
    supply: filter.supply, // 新增参数：供应商编码
  };

  for (const key in params) {
    if (!params[key]) {
      delete params[key];
    }
  }

  try {
    const res = await getGoodsList(params);
    console.log("表格数据：", res);
    if (res.code === "200") {
      tableData.value = res.data;
      // console.log('表格数据23333333333：', tableData.value);
      pagination.total = res.total;
      // pagination.currentPage = res.data.current_page;
    }
  } catch (error) {
    console.error("加载商品列表失败:", error);
    ElMessage.error("加载商品列表失败");
  }
};

// 查询按钮点击事件
const handleSearch = () => {
  // 重置到第一页
  pagination.currentPage = 1;
  loadGoodsData();
};



//返回放大图片url
const getImageUrl=(val:any)=>{
	return val.map((item: { url: any; })=>{
		return item.url
	})
}


// 每页条数改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  loadGoodsData(1, val);
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  loadGoodsData(val, pagination.pageSize);
};

// 加载分类数据
const loadCategoryData = async () => {
  try {
    const res = await getCategoryList();
    if (res.code === "200") {
      categoryOptions.value = res.data.info_list.map((item: any) => ({
        id: item.id,
        name: item.name,
      }));
    }
  } catch (error) {
    console.error("加载分类数据失败:", error);
  }
};

// 页面初始化时加载数据
onMounted(() => {
  loadGoodsData();
  loadCategoryData();
  loadSupplierData();
});
// 供应商选项
const supplyerOptions = ref<Option[]>([]);
// 分类选项
const categoryOptions = ref<Option[]>([]);
const loadSupplierData = async () => {
  try {
    const res = await getSupplierListAPI();
    if (res.code === "200") {
      supplyerOptions.value = res.data.info_list.map((item: any) => ({
        id: item.id,
        name: item.name,
      }));
    }
  } catch (error) {
    console.error("加载供应商数据失败:", error);
  }
};

// 获取供应商名称
const getSupplyerName = (supplyerId: number): string => {
  const supplyer = supplyerOptions.value.find((item) => item.id === supplyerId);
  return supplyer ? supplyer.name : "未知供应商";
};

// 获取分类名称
const getCategoryName = (categoryId: number): string => {
  const category = categoryOptions.value.find((item) => item.id === categoryId);
  return category ? category.name : "未分类";
};

// 对话框显示状态
const dialogVisible = ref(false);

// 表单数据（使用GoodsItem类型）
const form = reactive<GoodsItem>({
  id: 0,
  name: "",
  mealdesc: "",
  // stock: 0,
  supplyer: 0,
  category: 0,
  seq: 1,
  pictureList: [],
  spec: [],
});

const formRef = ref<FormInstance>();
// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  stock: [{ required: true, message: "请输入库存数量", trigger: "blur" }],
  supplyer: [{ required: true, message: "请选择供应商", trigger: "change" }],
  category: [{ required: true, message: "请选择分类", trigger: "change" }],
};

// 当前编辑的索引
let currentIndex = -1;

// 编辑操作
const handleEdit = (index: number, row: GoodsItem) => {
  currentIndex = index;
  Object.assign(form, {
    ...JSON.parse(JSON.stringify(row)),
    // 确保类型转换
    supplyer: row.supplyer,
    category: row.category,
  });
  dialogVisible.value = true;
};

// 删除操作
const handleDelete = async (index: number, row: GoodsItem) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm("确定要删除该商品吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 调用删除商品接口
    const requestData: DeleteGoodsRequest = {
      id: row.id as number,
    };

    const response = await deleteGoods(requestData);

    // 根据响应处理业务逻辑
    if (response.code === "200") {
      ElMessage.success(response.msg || "删除成功");

      // 从表格数据中移除商品
      tableData.value.splice(index, 1);

      // 如果需要，可以重新加载商品列表
      await loadGoodsData();
    } else {
      ElMessage.error(response.msg || "删除失败");
    }
  } catch (error) {
    console.error("删除商品失败:", error);
    ElMessage.error("删除商品失败，请稍后重试");
  }
};
// 添加操作
const handleAdd = () => {
  currentIndex = -1;
  Object.assign(form, {
    id: 0,
    name: "",
    mealdesc: "",
    stock: 0,
    supplyer: null,
    category: null,
    seq: 1,
    pictureList: [],
    spec: [],
    is_online: 0,
  });
  dialogVisible.value = true;
};

// 提交表单函数
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid && form.spec.length > 0) {
      try {
        const requestData =
          currentIndex === -1
            ? ({
                name: form.name,
                mealdesc: form.mealdesc,
                stock: form.stock,
                supplyer: form.supplyer.toString(),
                category: form.category.toString(),
                seq: form.seq,
                pictureList: form.pictureList,
                spec: form.spec,
                is_online: form.is_online,
              } as AddGoodsRequest)
            : ({
                id: form.id,
                name: form.name,
                mealdesc: form.mealdesc,
                stock: form.stock,
                supplyer: form.supplyer.toString(),
                category: form.category.toString(),
                seq: form.seq,
                pictureList: form.pictureList,
                spec: form.spec,
                is_online: form.is_online,
              } as EditGoodsRequest);

        const response =
          currentIndex === -1
            ? await addGoods(requestData as AddGoodsRequest)
            : await editGoods(requestData as EditGoodsRequest);

        if (response.code === "200") {
          ElMessage.success(response.msg || "操作成功");
          dialogVisible.value = false;
          loadGoodsData(); // 刷新列表
        } else {
          ElMessage.error(response.msg || "操作失败");
        }
      } catch (error) {
        console.error("请求出错:", error);
        ElMessage.error("操作失败，请稍后重试");
      }
    } else {
      ElMessage.error("请完整填写表格和添加商品规格");
      console.log("error submit!", fields);
    }
  });
};
// 添加规格
const addSpec = () => {
  form.spec.push({
    specname: "",
    price: 0,
    stock: 0,
    seq: form.spec.length + 1,
  });
};

// 删除规格
const removeSpec = (index: number) => {
  form.spec.splice(index, 1);
};

// 图片拖拽结束的事件
const onEnd = () => {
  // 更新图片的 seq 值
  form.pictureList.forEach((item, index) => {
    item.seq = index + 1;
  });
  console.log("拖拽结束，更新后的图片列表：", form.pictureList);
};

// 规格拖拽结束的事件
const onSpecEnd = () => {
  // 更新规格的 seq 值
  form.spec.forEach((item, index) => {
    item.seq = index + 1;
  });
  console.log("规格拖拽结束，更新后的规格列表：", form.spec);
};
</script>

<style scoped lang="scss">
/* 顶部操作区start */
.filter-container {
  margin-bottom: 20px;

  .filterSelecter {
    width: 200px;
    margin-right: 10px;
  }
}

/* 规格start */
.addSpecButton {
  width: 100%;
  /* background-color: red; */
  margin-bottom: 30px 0;
}

/* 规格end */

/* 总体布局 start*/
.goods-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;

  .addGoodsButton {
    /* background-color: red; */
    width: 100%;
    margin-bottom: 20px;
  }
}

/* 总体布局 end*/

/* 底部确认和取消按钮 start*/
.footer {
  width: 80%;
  height: 30px;
  /* background-color: red; */
  display: flex;

  justify-content: center;
  align-items: center;

  .button {
    margin-left: 20px;
  }
}
</style>
